package com.xyhy.core.utils.crypto;

import java.security.MessageDigest;
import java.util.Map.Entry;
import java.util.SortedMap;

import com.xyhy.core.utils.code.CodeUtil;

public class Md5Util {
  public static String generateSign(SortedMap<String, String> signMaps, String mchKey) {
    StringBuffer sb = new StringBuffer();

    // 字典序
    for (Entry<String, String> signMap : signMaps.entrySet()) {
      String key = (String) signMap.getKey();
      String value = (String) signMap.getValue();

      // 为空不参与签名、参数名区分大小写
      if (null != value && !"".equals(value) && !"sign".equals(key) && !"key".equals(key)) {
        sb.append(key).append("=").append(value).append("&");
      }
    }

    // 拼接key
    sb.append("key=").append(mchKey);
    // MD5加密
    String sign = MD5Encode(sb.toString(), "UTF-8").toUpperCase();
    return sign;
  }

  private static String MD5Encode(String origin, String charsetname) {
    String resultString = null;
    try {
      resultString = new String(origin);
      MessageDigest md = MessageDigest.getInstance("MD5");
      if (charsetname == null || "".equals(charsetname))
        resultString = CodeUtil.byteArrayToHexString(md.digest(resultString.getBytes()));
      else resultString = CodeUtil.byteArrayToHexString(md.digest(resultString.getBytes(charsetname)));
    } catch (Exception exception) {
    }
    return resultString;
  }

}
